package reentrantlock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

public class UnfairLock {

    /*
    unfairlock非公平锁，只会允许线程先cas一次，如果不成功，仍然会入队，且无论该线程的
    等级是高是低，都会排队到队尾
     */
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock reentrantLock = new ReentrantLock(false);
        CountDownLatch countDownLatch = new CountDownLatch(4);
        new Thread(() -> {
            reentrantLock.lock();
            System.out.println("i am thread 1 ,and i get lock");
            try {
                Thread.sleep(3*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            reentrantLock.unlock();
            countDownLatch.countDown();
        }).start();
        new Thread(() -> {
            reentrantLock.lock();
            System.out.println("i am thread 2 ,and i get lock");
            reentrantLock.unlock();
            countDownLatch.countDown();
        }).start();
        new Thread(() -> {
            reentrantLock.lock();
            System.out.println("i am thread 3 ,and i get lock");
            reentrantLock.unlock();
            countDownLatch.countDown();
        }).start();
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread boss = new Thread(() -> {
            reentrantLock.lock();
            System.out.println("i am thread 4 and i am boss ,and i get lock");
            reentrantLock.unlock();
            countDownLatch.countDown();
        });
        boss.setPriority(10);
        boss.start();


        countDownLatch.await();
    }
}
